<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('system_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable()->comment('操作用户ID');
            $table->string('action', 100)->comment('操作类型');
            $table->string('module', 100)->comment('操作模块');
            $table->string('target_type', 100)->nullable()->comment('操作对象类型');
            $table->unsignedBigInteger('target_id')->nullable()->comment('操作对象ID');
            $table->text('description')->comment('操作描述');
            $table->json('old_data')->nullable()->comment('操作前数据');
            $table->json('new_data')->nullable()->comment('操作后数据');
            $table->string('ip_address', 45)->nullable()->comment('IP地址');
            $table->string('user_agent')->nullable()->comment('用户代理');
            $table->enum('level', ['info', 'warning', 'error', 'critical'])->default('info')->comment('日志级别');
            $table->json('context')->nullable()->comment('上下文信息');
            $table->timestamps();
            
            // 外键约束
            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            
            // 索引
            $table->index(['user_id', 'created_at']);
            $table->index(['action', 'module']);
            $table->index(['target_type', 'target_id']);
            $table->index(['level', 'created_at']);
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('system_logs');
    }
};
